package org.cy.evolution.net.http.converter.json;

import android.support.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class FastJsonConvertFactory extends Converter.Factory {

    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");

    private ParserConfig parserConfig = ParserConfig.getGlobalInstance();
    private int featureValue = JSON.DEFAULT_PARSER_FEATURE;

    private Feature[] features = new Feature[0];

    private SerializeConfig config = null;
    private SerializerFeature[] serializerFeatures = new SerializerFeature[0];

    private static FastJsonConvertFactory INSTANCE = null;

    public static FastJsonConvertFactory create() {
        if ( null == INSTANCE) {
            INSTANCE = new FastJsonConvertFactory();
        }
        return INSTANCE;
    }


    @Nullable
    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return new FastJsonRequestBodyConverter<>(MEDIA_TYPE, config, serializerFeatures);
    }

    @Nullable
    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new FastJsonResponseBodyConverter<>(type, parserConfig, featureValue, features);
    }

    public void setFeatures(Feature... features) {
        this.features = features;
    }

    public void setConfig(SerializeConfig config) {
        this.config = config;
    }

    public void setSerializerFeatures(SerializerFeature... serializerFeatures) {
        this.serializerFeatures = serializerFeatures;
    }
}
